<!DOCTYPE html>
<html>
<head>
    <title>Fixed PeerJS Server Test</title>
    <script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
    <style>
        .status { margin: 10px; padding: 10px; border: 1px solid #ccc; }
        input, button { padding: 8px; margin: 5px 0; }
        button { background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        button:hover { background-color: #45a049; }
        .error { color: red; background-color: #ffebee; }
        .success { color: green; background-color: #e8f5e9; }
        .container { max-width: 800px; margin: 20px auto; padding: 20px; }
        h1 { color: #333; }
    </style>
</head>
<body>
    <div class="container">
        <h1>PeerJS P2P 连接测试</h1>
        <div class="status" id="status">连接中...</div>
        <div class="status" id="peerId"></div>
        <div class="status" id="connectionInfo"></div>
        
        <!-- 连接表单 -->
        <div class="status">
            <h3>连接到其他 Peer</h3>
            <input type="text" id="remotePeerId" placeholder="输入远程 Peer ID">
            <button onclick="connectToPeer()">连接</button>
        </div>
        
        <!-- 消息区域 -->
        <div class="status">
            <h3>消息</h3>
            <div id="messages" style="height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;"></div>
            <input type="text" id="messageInput" placeholder="输入消息">
            <button onclick="sendMessage()">发送</button>
        </div>
        
        <div class="status" id="debugInfo" style="font-family: monospace; font-size: 0.9em;"></div>
    </div>

    <script>
        const peer = new Peer(undefined, {
            host: '192.168.50.177',
            port: 3000, 
            secure: false, 
            // 核心修改：path只保留Nginx代理的路径，无需加/peerjs（服务器会自动处理）
            path: '/peerjs-server',  
            debug: 2,
            config: {
                iceServers: [
                    { urls: 'stun:stun.l.google.com:19302' },
                    { urls: 'stun:stun1.l.google.com:19302' }
                ]
            }
        });

        peer.on('open', (id) => {
            document.getElementById('status').className = 'status success';
            document.getElementById('status').textContent = '✅ Connection successful!';
            document.getElementById('peerId').textContent = `Peer ID: ${id}`;
            document.getElementById('connectionInfo').textContent = 
                `Connected to: https://${peer._options.host}:${peer._options.port}${peer._options.path}`;
            console.log('Peer ID:', id);
        });

        peer.on('error', (error) => {
            document.getElementById('status').className = 'status error';
            document.getElementById('status').textContent = `❌ Error: ${error.type}`;
            document.getElementById('connectionInfo').textContent = `Message: ${error.message}`;
            document.getElementById('debugInfo').textContent = `Debug: ${JSON.stringify(error, null, 2)}`;
            console.error('Error:', error);
        });

        // 存储活动连接
        let activeConnection = null;
        
        // 连接到远程 Peer
        function connectToPeer() {
            const remoteId = document.getElementById('remotePeerId').value;
            if (!remoteId) {
                alert('请输入远程 Peer ID');
                return;
            }

            // 创建连接
            const conn = peer.connect(remoteId);

            // 连接建立时触发
            conn.on('open', function() {
                activeConnection = conn;
                document.getElementById('connectionInfo').textContent += `\n✅ 已连接到 Peer: ${remoteId}`;
                addMessage(`系统: 已连接到 ${remoteId}`);

                // 监听数据接收
                conn.on('data', function(data) {
                    addMessage(`收到: ${data}`);
                });

                // 监听连接关闭
                conn.on('close', function() {
                    addMessage(`系统: 与 ${remoteId} 的连接已关闭`);
                    activeConnection = null;
                });
            });

            // 连接错误处理
            conn.on('error', function(err) {
                alert(`连接错误: ${err}`);
                document.getElementById('connectionInfo').textContent += `\n❌ 连接到 ${remoteId} 失败: ${err}`;
            });
        }

        // 接收连接请求
        peer.on('connection', function(conn) {
            activeConnection = conn;
            document.getElementById('connectionInfo').textContent += `\n✅ 收到来自 ${conn.peer} 的连接请求`;
            addMessage(`系统: 已接受来自 ${conn.peer} 的连接`);

            // 监听数据接收
            conn.on('data', function(data) {
                addMessage(`收到: ${data}`);
            });

            // 监听连接关闭
            conn.on('close', function() {
                addMessage(`系统: 与 ${conn.peer} 的连接已关闭`);
                activeConnection = null;
            });
        });

        // 发送消息
        function sendMessage() {
            if (!activeConnection) {
                alert('请先建立连接');
                return;
            }

            const message = document.getElementById('messageInput').value;
            if (!message) {
                alert('请输入消息');
                return;
            }

            activeConnection.send(message);
            addMessage(`发送: ${message}`);
            document.getElementById('messageInput').value = '';
        }

        // 添加消息到消息区域
        function addMessage(message) {
            const messagesDiv = document.getElementById('messages');
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        // 10秒超时检测
        setTimeout(() => {
            if (document.getElementById('status').textContent === '连接中...') {
                document.getElementById('status').className = 'status error';
                document.getElementById('status').textContent = '❌ 连接超时';
                document.getElementById('connectionInfo').textContent = '请检查代理服务器和 PeerServer 是否运行正常';
            }
        }, 10000);
    </script>
</body>
</html>
